package logic.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.location.LocationManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.cacche.Cache;
import com.google.gson.Gson;
import com.shwread.android.qysw10000227.R;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.Math.PI;


public class Util
{
	public static final byte			  SCAN_TYPE_ALL		 = 0;
	public static final byte			  SCAN_TYPE_TXT		 = 1;
	public static final byte			  SCAN_TYPE_EPUB	 = 2;
	public static final byte			  SCAN_TYPE_PDF		 = 3;
	public static final byte			  SCAN_TYPE_OFFICE	 = 4;
	public static final byte			  SCAN_TYPE_OTHER	 = 5;
	public static final ArrayList<String> readFileTypeAll	 = new ArrayList<String>();
	public static final ArrayList<String> readFileTypeTxt	 = new ArrayList<String>();
	public static final ArrayList<String> readFileTypeEpub	 = new ArrayList<String>();
	public static final ArrayList<String> readFileTypePdf	 = new ArrayList<String>();
	public static final ArrayList<String> readFileTypeOffice = new ArrayList<String>();
	public static final ArrayList<String> readFileTypeOther	 = new ArrayList<String>();
	private final static double R_ = 6371393; // 地球的半径
	private static final Pattern REG_UNICODE = Pattern.compile("[0-9A-Fa-f]{4}");
	private static final Pattern EN_CODE	 = Pattern.compile("[A-Za-z]{4}");
	private static final double EARTH_RADIUS = 6378137.0;
	static DecimalFormat df2 = new DecimalFormat("#0.00");
	private static Toast sToast;
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	private static SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
	private static SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm:ss");
	
	static
	{
		/** txt */
		readFileTypeTxt.add("txt");

		readFileTypeEpub.add("epub");

		readFileTypePdf.add("pdf");
		/** office */
		readFileTypeOffice.add("doc");
		//		readFileTypeOffice.add("xls");
		//		readFileTypeOffice.add("ppt");
		//		readFileTypeOffice.add("docx");
		//		readFileTypeOffice.add("xlsx");
		//		readFileTypeOffice.add("pptx");
		/** other */
		readFileTypeOther.add("rtf");
		readFileTypeOther.add("umd");

		//		readFileTypeOther.add("log");

		readFileTypeAll.addAll(readFileTypeTxt);
		readFileTypeAll.addAll(readFileTypeEpub);
		readFileTypeAll.addAll(readFileTypePdf);
		readFileTypeAll.addAll(readFileTypeOffice);
		readFileTypeAll.addAll(readFileTypeOther);
	}
	
	/**
	 * 格式化手机号码(如：123****5678)
	 *
	 * @param phone
	 * @return
	 */
	public static String formatPhone(String phone) {
		if (isNotEmpty(phone) && phone.length() > 7) { return new StringBuffer(phone.substring(0, 3)).append("****").append(phone.substring(7, phone.length())).toString(); }
		return phone;
	}
	
	public static String filterName(String path) {
		String result = path;
		int index = path.lastIndexOf(File.separator);
		if (index != -1)
		{
			result = path.substring(index + 1);
		}
		index = result.lastIndexOf(".");
		if (index != -1)
		{
			result = result.substring(0, index);
		}
		return result;
	}
	
	/**
	 * @Title: getpercent
	 * @Description: 计算百分比
	 * @param @param
	 *            index
	 * @param @param
	 *            count
	 * @param @param
	 *            minimum小数点后面的位数
	 * @param @return
	 *            设定文件
	 * @return String 返回类型
	 * @throws
	 *             @date
	 *             2012-2-17 上午10:07:24
	 */
	public static String getPercent(long index, long count, int minimum) {
		if (count == 0) { return "0%"; }
		DecimalFormat format = new DecimalFormat("###,##0");
		format.setMinimumFractionDigits(minimum);
		double per = ((double) index / count) * 100;
		return format.format(per);
	}
	
	public static String filterExt(String path) {
		String result = "";
		int index = path.lastIndexOf(".");
		if (index != -1)
		{
			result = path.substring(index + 1);
		}
		return result.toLowerCase();
	}
	
	public static void ToastShow(Context context, CharSequence charSequence) {
		if (sToast == null)
		                    sToast = Toast.makeText(context, charSequence, Toast.LENGTH_SHORT);
		else
		                    sToast.setText(charSequence);
		sToast.show();
	}
	
	public static void ToastShow(Context context, int id) {
		if (sToast == null)
		                    sToast = Toast.makeText(context, id, Toast.LENGTH_SHORT);
		else
		                    sToast.setText(id);
		sToast.show();
	}
	
	public static String getFormatDate(long time) {
		return sdf.format(new Date(time));
	}

	public static Date getStringtoDate(String strTime) {
		Date date = null;
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			date = sdf.parse(strTime);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
		}
		return date;
	}

	public static String getFormatTime(long time) {
		return sdf2.format(new Date(time));
	}

	public static String getFormatTimeforSecond(long time) {
		return sdf3.format(new Date(time));
	}

	/**
	 * 获取当前时间日期
	 *
	 * @param format
	 *            自定义格式,例：yyyy-MM-dd hh:mm:ss
	 * @return
	 */
	public static String getFormatTime(String format) {
		Date date = new Date();
		// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat(format);
		String time = df.format(date);
		return time;
	}

	/**
	 * 获取指定格式的时间
	 *
	 * @param format
	 *            自定义格式,例：yyyy-MM-dd hh:mm:ss
	 * @param time
	 *            时间(毫秒)
	 * @return
	 */
	public static String getFormatTime(String format, long time) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		String result = df.format(new Date(time));
		return result;
	}
															 
	public static String getPercent(long cur, long len) {
		float fPercent = (float) (cur * 1.0 / len);
		return df2.format(fPercent * 100);
	}

	/**
	 * 计算文件的大小
	 *
	 * @param filesize
	 * @return
	 */
	public static String getFileSizeString(long filesize) {
		String sizeString = null;
		float size = 0;
		if (filesize < 1024)
		{
			//xx b
			size = filesize;
			sizeString = df2.format(size) + " B";
		}
		else if (filesize < 1024 * 1024)
		{
			//xx k
			size = (float) (filesize / 1024);
			sizeString = df2.format(size) + " KB";
		}
		else
		{
			//xx m
			size = (float) (filesize / (1024 * 1024));
			sizeString = df2.format(size) + " MB";
		}
		return sizeString;
	}

	public static String getString(String str, int maxsize) {
		if (str.length() > maxsize)
		{
			str = str.substring(0, maxsize);
		}
		return str;
	}

	public static String removeNameSpace(String ns_tag) {
		String[] ns__tag = ns_tag.split(":");
		return ns__tag[ns__tag.length - 1];
	}

	public static void showToast(Context mContext, int resId) {
		Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
	}

	public static void showToast(Context mContext, String text) {
		Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
	}
															 
	/**
	 * 手机号验证
	 *
	 * @param str
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,6,7,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}
	
	/**
	 * 判断String为空
	 *
	 * @param string
	 * @return
	 */
	public static boolean isEmpty(String string) {
		return (string == null || "".equalsIgnoreCase(string.trim()) || "null".equals(string));
	}
	
	public static String NUllToString(String value) {
		if (Util.isEmpty(value))
		{
			value = "";
		}
		return value;
	}
	
	/**
	 * 判断String不为空
	 *
	 * @param string
	 * @return
	 */
	public static boolean isNotEmpty(String string) {
		return string != null && string.trim().length() > 0;
	}
	
	public static boolean isReaderFileType(File file) {
		if (file != null && file.exists() && file.isFile() && file.getPath().indexOf(".") != -1)
		{
			String path = file.getPath();
			String type = path.substring(path.lastIndexOf(".") + 1, path.length());
			return readFileTypeAll.contains(type);
		}
		return false;
	}
	
	public static byte getType(File file) {
		if (file != null && file.exists() && file.isFile() && file.getPath().indexOf(".") != -1)
		{
			String path = file.getPath();
			String type = path.substring(path.lastIndexOf(".") + 1, path.length());
			if (readFileTypeTxt.contains(type))
			                                    return SCAN_TYPE_TXT;
			else if (readFileTypeEpub.contains(type))
			                                          return SCAN_TYPE_EPUB;
			else if (readFileTypePdf.contains(type))
			                                         return SCAN_TYPE_PDF;
			else if (readFileTypeOffice.contains(type))
			                                            return SCAN_TYPE_OFFICE;
			else if (readFileTypeOther.contains(type))
			                                           return SCAN_TYPE_OTHER;
			else
			                                           return SCAN_TYPE_ALL;
		}
		return SCAN_TYPE_ALL;
	}
	
	public static String getProcess(double paycount) {
		DecimalFormat df = new DecimalFormat("0.0");
		return df.format(paycount) + "%";
	}
	
	/**
	 * bitmap转成byte[] 获得限制大小的图片JPEG数据 (用于头像)
	 *
	 * @param bitmap
	 *            图片
	 * @param quality
	 *            起始jpeg图片质量
	 * @param limitSize
	 *            限制的图片大小
	 */
	public static byte[] getImageDataByLimitSize(Bitmap bitmap, int quality, int limitSize) {
		if (bitmap == null || limitSize <= 0)
		                                      return null;

		if (quality <= 0) { return null; }

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, quality, baos);
		byte[] bytes = baos.toByteArray();

		if (bytes.length > limitSize)
		{
			bytes = null;
			bytes = getImageDataByLimitSize(bitmap, quality - 10, limitSize);
		}

		return bytes;
	}
	
	/**
	 * 获取文件写入路径，无视错误
	 *
	 * @param fileName
	 *            文件全名
	 * @return 返回路径，返回null则拒绝写入操作
	 */
	public static String getWritePathIgnoreError(String fileName) {
		try
		{
			MultiCardFilePath path = MultiCard.getInstance().getWritePath(fileName);
			return path.getFilePath();
		}
		catch (LimitSpaceUnwriteException e)
		{
			e.printStackTrace();
		}
		catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 根据文件类型检查外置及内置存储卡是否有空间可写
	 *
	 * @param fileType
	 *            文件类型
	 * @param type
	 *            检查范围,0表示所有,1表示只检查外置
	 * @return
	 */
	public static boolean isLimitSDCardSpaceForWrite(int fileType, int type) {
		return MultiCard.getInstance().checkSDCardSpace(fileType, type);
	}
	
	/**
	 * 根据文件类型检查外置及内置存储卡是否超过预警空间
	 *
	 * @param fileType
	 *            文件类型
	 * @param type
	 *            检查范围,0表示所有,1表示只检查外置
	 * @return
	 */
	public static boolean isLimitSDCardSpaceForWriteWarning(int fileType, int type) {
		return MultiCard.getInstance().islimitSpaceWarning(fileType, type);
	}
	
	/**
	 * 判断存储卡空间(外置、内置存储卡是否有空间可写)
	 *
	 * @param context
	 * @param fileType
	 *            文件类型
	 * @param type
	 *            检查范围,0表示所有,1表示外置
	 * @param bNeedTip
	 *            是否要做出提示语
	 * @return true表示无存储卡或无空间可写,false表示ok
	 */
	public static boolean isSDCardSapceForWriteWithTip(Context context, int fileType, int type, boolean bNeedTip) {
		if (type == 0 && !Util.isSDcardExist())
		{
			if (bNeedTip)
			{
				Util.showToast(context, R.string.image_save_sdcard_deny);
			}
			return true;
		}
		else if (type == 1 && !Util.isExternalSDCardExist())
		{
			if (bNeedTip)
			{
				Util.showToast(context, R.string.image_save_sdcard_deny);
			}
			return true;
		}

		if (!Util.isLimitSDCardSpaceForWrite(fileType, type))
		{
			if (bNeedTip)
			{
				Util.showToast(context, R.string.sdcard_not_enough);
			}
			return true;
		}

		if (!Util.isLimitSDCardSpaceForWriteWarning(fileType, type))
		{
			if (bNeedTip)
			{
				Util.showToast(context, R.string.sdcard_not_enough_warning);
			}
		}

		return false;
	}
	
	/**
	 * 判断是否有SDCARD
	 *
	 * @return
	 */
	public static boolean isSDcardExist() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{
			return true;
		}
		else
		{
			return false;
		}

	}
	
	/**
	 * 判断是否有外置存储卡
	 *
	 * @return
	 */
	public static boolean isExternalSDCardExist() {
		return MultiCard.getInstance().isExternalSDCardExist();
	}
	
	/**
	 * 根据时间格式得到时间段
	 *
	 * @return 刚刚,?分钟前,?小时前(24小时内) 昨天 时:分(24小时之前) 前天 时:分(48小时之前) 年-月-日
	 *         时:分(72小时之前)
	 */
	public static String getTimeByDuration(long time_l) {
		try
		{
			SimpleDateFormat formatter = new SimpleDateFormat("MMdd");
			Date date = new Date(time_l);
			String date_s = formatter.format(new Date());
			String sDay = formatter.format(date);
			int index = (Integer.valueOf(sDay) - Integer.valueOf(date_s));
			if (index == 0)
			{
				formatter = new SimpleDateFormat("HH:mm");
				return formatter.format(date);
			}
			else if (index == -1)
			{
				return "昨天";
			}
			else if (index == -2)
			{
				return "前天";
			}
			else
			{
				formatter = new SimpleDateFormat("yyyy");
				String year = formatter.format(date);
				formatter = new SimpleDateFormat("MM");
				String yue = formatter.format(date);
				formatter = new SimpleDateFormat("dd");
				String ri = formatter.format(date);
				return Integer.parseInt(year) + "-" + Integer.parseInt(yue) + "-" + Integer.parseInt(ri);
			}
		}
		catch (Exception e)
		{
			return "";
		}
	}
	
	public static int dp2px(Context context, int dp) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dp * scale + 0.5f);
	}
	
	public static float getTextWidth(float textSize, String text) {
		Paint paint = new Paint();
		paint.setTextSize(textSize);
		return paint.measureText(text);
	}
	
	public static final int getBitMapWidth(int res, Context context) {
		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), res);
		return bitmap.getWidth();
	}
	
	public static final int getBitMapHeight(int res, Context context) {
		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), res);
		return bitmap.getHeight();
	}
	
	public static byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}
	
	public static Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0)
		{
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		}
		else
		{
			return null;
		}
	}
	
	public static Bitmap getRoundBitmap(Bitmap src) {
		float radius = src.getWidth() / 2f;
		Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);

		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setColor(Color.RED);

		canvas.drawCircle(radius, radius, radius, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

		canvas.drawBitmap(src, 0, 0, paint);

		return bitmap;
	}
	
	/**
	 * 隐藏键盘
	 *
	 * @param mInputMethodManager
	 * @param mView
	 */
	public static void hideInputMethodManager(Context mContext, View view) {
		final InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (inputMethodManager != null && view != null)
		{
			inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}
	
	//显示键盘
	public static InputMethodManager showInputMethodManager(Context mContext) {
		final InputMethodManager mInputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		mInputMethodManager.toggleSoftInput(InputType.TYPE_CLASS_PHONE, InputMethodManager.HIDE_NOT_ALWAYS);
		return mInputMethodManager;
	}
	
	/***
	 * 判断字符串是否是数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;)
		{
			if (!Character.isDigit(str.charAt(i))) { return false; }
		}
		return true;
	}
	
	/**
	 * 检查是否注册验证码
	 *
	 * @param num
	 * @param msg
	 * @return
	 */
	public static String checkVerifySms(String msg) {
		String verify = null;

		String regex = "验证码:(.+)[(]本短信仅仅为了验证您的手机号码，您可以忽略[)]【天翼阅读】";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(msg.trim());
		if (matcher.find())
		{
			verify = matcher.group(1).trim();
			//#debug
			base.tina.core.log.LogPrinter.d(null, "验证码:" + verify);

		}

		return verify;
	}
	
	public static String formetFileSize(long fileSize) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileSize < 1024)
		{
			fileSizeString = df.format((double) fileSize) + "B";
		}
		else if (fileSize < 1048576)
		{
			fileSizeString = df.format((double) fileSize / 1024) + "K";
		}
		else if (fileSize < 1073741824)
		{
			fileSizeString = df.format((double) fileSize / 1048576) + "M";
		}
		else
		{
			fileSizeString = df.format((double) fileSize / 1073741824) + "G";
		}
		return fileSizeString;
	}
	
	public static String getFileItemCount(Context context, String fileCount) {
		return context.getResources().getString(R.string.file_item_count, fileCount);
	}
	
	/**
	 * * 判断输入字符是否为有效汉字
	 *
	 * @param str
	 *            字符
	 * @return 是否合法汉字
	 */
	public static boolean isValidHan(String str) {
		String regex = "[\u4e00-\u9fa5]*";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}
	
	/**
	 * TODO 待确认完整的有效字符！！！！！！
	 * 判断字符串是否有效
	 *
	 * @param str
	 * @return
	 */
	public static boolean isValid(String str) {
		return str.matches("[A-Za-z0-9\u4e00-\u9fa5《》？、。，；：‘“【】）（……￥！~· ,/./?<>@#/$%&!;'\":|/+=_{}]*");
	}
	
	public static boolean isStringValid(String str) {
		return str.matches("[A-Za-z0-9]*");
	}
	
	/**
	 *
	 */

	public static boolean isIncludeSpecificSymbol(String str) {
		return !(str.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "").length() == str.length());
		//		return str.replaceAll("[^\\dA-Za-z\u3007\u3400-\u4DB5\u4E00-\u9FCB\uE815-\uE864]", "").length()==0;
	}

	/**
	 * Convert the whole String object.
	 *
	 * @param str
	 * @return
	 */
	public static String string2Unicode(String str) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length(); i++)
		{
			String tmpStr = Integer.toHexString(str.charAt(i));
			if (tmpStr.length() < 4)
			{
				sb.append("\\u00");
			}
			else
			{
				sb.append("\\u");
			}
			sb.append(tmpStr);
		}
		return sb.toString();
	}
											 
	/**
	 * Just convert Chinese String
	 *
	 * @param str
	 * @return
	 */
	public static String chinese2Unicode(String str) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length(); i++)
		{
			String tmpStr = Integer.toHexString(str.charAt(i));

			if (tmpStr.length() < 4)
			{
				sb.append(str.charAt(i));
			}
			else
			{
				sb.append("\\u");
				sb.append(tmpStr);
			}
		}
		return sb.toString();
	}
	
	public static String unicode2String(String str) {
		StringBuilder sb = new StringBuilder();
		int len = str.length();
		for (int i = 0; i < len; i++)
		{
			char c1 = str.charAt(i);
			if (c1 == '\\' && i < len - 1)
			{
				char c2 = str.charAt(++i);
				if (c2 == 'u' && i <= len - 5)
				{
					String tmp = str.substring(i + 1, i + 5);
					Matcher matcher = REG_UNICODE.matcher(tmp);
					if (matcher.find())
					{
						sb.append((char) Integer.parseInt(tmp, 16));
						i = i + 4;
					}
					else
					{
						sb.append(c1).append(c2);
					}
				}
				else
				{
					sb.append(c1).append(c2);
				}
			}
			else
			{
				sb.append(c1);
			}
		}
		return sb.toString();
	}
	
	public static byte[] file2Byte(String filePath) throws Exception {
		byte[] buffer = null;
		File file = new File(filePath);
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		while ((n = fis.read(b)) != -1)
		{
			bos.write(b, 0, n);
		}
		fis.close();
		bos.close();
		buffer = bos.toByteArray();
		return buffer;
	}
	
	public static void byte2File(byte[] buf, String filePath, String fileName) throws Exception {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		File dir = new File(filePath);
		if (!dir.exists() && dir.isDirectory())
		{
			dir.mkdirs();
		}
		file = new File(filePath + File.separator + fileName);
		fos = new FileOutputStream(file);
		bos = new BufferedOutputStream(fos);
		bos.write(buf);
		if (bos != null)
		                 bos.close();
		if (fos != null)
		                 fos.close();
	}
	
	/**
	 * 从缓存中获取bitmap
	 *
	 * @param context
	 * @param contentId
	 * @param url
	 * @param imgView
	 */
	public static void loadImg(Context context, String contentId, String url, final ImageView imgView) {
		Cache.getInstance(context).getImage(contentId, url, new Handler()
		{

			@Override
			public void handleMessage(Message msg) {
				if (msg.obj != null)
		                             imgView.setImageBitmap((Bitmap) msg.obj);
			}

		});
	}
	
	public static boolean isStringEmpty(String str) {
		if (str == null) { return true; }

		if (str.length() <= 0) { return true; }

		return false;
	}
	
	public static int OxStringtoInt(String ox) throws Exception {
		ox = ox.toLowerCase();
		if (ox.startsWith("0x"))
		{
			ox = ox.substring(2, ox.length());
		}

		if (ox.startsWith("#"))
		{
			ox = ox.substring(1, ox.length());
		}

		if (ox.length() > 8)
		{
			ox = ox.substring(0, 8);
		}
		String ff = "ffffffff";
		int misCount = 8 - ox.length();
		if (misCount > 0)
		{
			String misFf = ff.substring(0, misCount);
			ox = misFf + ox;
		}

		int ri = 0;
		int oxlen = ox.length();
		for (int i = 0; i < oxlen; i++)
		{
			char c = ox.charAt(i);
			int h;
			if (('0' <= c && c <= '9'))
			{
				h = c - 48;
			}
			else if (('a' <= c && c <= 'f'))
			{
				h = c - 87;

			}
			else if ('A' <= c && c <= 'F')
			{
				h = c - 55;
			}
			else
			{
				throw (new Exception("not a integer "));
			}
			byte left = (byte) ((oxlen - i - 1) * 4);
			ri |= (h << left);
		}
		return ri;
	}
	
	public static Object jsonStringToObject(String jsonStr, Class<?> classOf) {
		Object object = null;
		try
		{
			Gson gson = new Gson();
			object = gson.fromJson(jsonStr, classOf);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return object;
	}
	
	/**
	 * @Title: addUrlTimestamp
	 * @Description: 在url后面增加时间戳骗过浏览器的缓存
	 * @param @param url
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	public static String addUrlTimestamp(String url) {
		long timstamp = System.currentTimeMillis();

		if (url.indexOf("?") > 0)
		{
			url += "&t=" + timstamp;
		}
		else
		{
			url += "?t=" + timstamp;
		}
		return url;
	}
	
	public static String getJsonStringByEntity(Object o) {
		String strJson = "";
		Gson gson = new Gson();
		strJson = gson.toJson(o);
		return strJson;
	}
	
	/**
	 * 计算地球上两点之间的距离
	 *
	 * @param lat1
	 * @param longt1
	 * @param lat2
	 * @param longt2
	 * @return
	 * @throws Exception
	 */
	public static double distance(double lat1, double longt1, double lat2, double longt2) throws Exception {
		double x, y, distance;
		x = (longt2 - longt1) * PI * R_ * Math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;
		y = (lat2 - lat1) * PI * R_ / 180;
		distance = Math.hypot(x, y);
		return Double.valueOf(new DecimalFormat("0.00").format(distance).toString());
	}
	
	/**
	 * 是否是固话+手机号码
	 *
	 * @param str
	 * @return
	 */
	public static boolean isTelephoneNumber(String str) {
		if (TextUtils.isEmpty(str)) { return false; }
		if (!str.matches("^\\d{3,}$")) { return false; }
		if (str.matches("^1[34578]\\d*")) { return str.length() == 11; }
		return LandlineTelephoneUtil.isLandlineTelephone(str);
	}

	/**
	 * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
	 *
	 * @param context
	 * @return true 表示开启
	 */
	public static final boolean gPSIsOPen(final Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		// 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
		boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		// 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
		boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		if (gps || network) { return true; }
		return false;
	}

	/**
	 * 判断GPS是否开启
	 * @param context
	 * @return true 表示开启
	 */
	public static final boolean gpsIsOpen(final Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		// 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
		boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		return gps;
	}

	/**
	 * 根据俩地经纬度求距离
	 *
	 */

	public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
		double Lat1 = rad(latitude1);
		double Lat2 = rad(latitude2);
		double a = Lat1 - Lat2;
		double b = rad(longitude1) - rad(longitude2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	private static double rad(double d) {
		return d * Math.PI / 180.0;
		}
}
